# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/7/20
import os
from submodules.common.lib.log_ import logger




def kill_task_by_pid(pid):
    cmd_tmp = f"taskkill /F /T /PID {pid}"
    logger.info(cmd_tmp)
    res = os.popen(cmd_tmp).read()
    logger.info(res)


def kill_task_by_name(name):
    '''
        script_name = "team_task.py"
    :return:
    '''
    # 获取相关进程信息
    cmd_tmp = f"wmic process get Caption,CommandLine,ExecutablePath,ProcessId|findstr {name}"
    logger.info(cmd_tmp)
    cmd_res = os.popen(cmd_tmp).read()

    # 结构化进程信息
    process_info_raw_list = cmd_res.split("\n")
    logger.info(process_info_raw_list)
    process_info_list = []
    for process_info_raw in process_info_raw_list:
        if process_info_raw.__len__() > 0:
            process_item_info_list = []
            process_item_info_list_tmp = process_info_raw.split(" ")
            for process_item_info_tmp in process_item_info_list_tmp:
                if process_item_info_tmp != "":
                    process_item_info_list.append(process_item_info_tmp)

            process_info_list.append(process_item_info_list)

    logger.info(process_info_list)

    # 按pid停止进程
    for process_info in process_info_list:
        pid = process_info[-1]
        kill_task_by_pid(pid)


if __name__ == '__main__':
    def test_kill_task_by_name():
        name = "YoudaoNote.exe"
        name = "Nox.exe"
        kill_task_by_name(name)


    test_kill_task_by_name()
